package com.yj.lcj.login.config;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yj.lcj.config.CacheConstants;
import com.yj.lcj.config.SessionManager;
import com.yj.lcj.exception.ApiRespones;
import com.yj.lcj.login.mapper.AppUserMapper;
import com.yj.lcj.login.pojo.AppUser;
import com.yj.lcj.login.service.AppUserService;
import com.yj.lcj.respones.CodeError;
import com.yj.lcj.respones.Result;
import com.yj.lcj.utils.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
@Slf4j
public class LoginConfig {

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private AppUserService appUserService;;

    @Autowired
    private AppUserMapper appUserMapper;

    // 查询构造器


    /**
     * 获取验证码
     * @param phone 手机号
     * @return 验证码
     * @throws ApiRespones
     */
    public Result getCode(String phone) throws ApiRespones{
        if (phone.length() != 11 ){
            throw  new ApiRespones("408","手机号不正确");
        }
        if (phone == null){
            throw  new ApiRespones("408","请输入手机号");
        }
        // 获取随机数
        Random random = new Random();
        int i = random.nextInt(100000)+1;
        tokenManager.setKey(CacheConstants.Cache_KEY+phone,i);
        log.info("验证码:"+i);
        return new Result().success("获取成功",200,i);
    }

    /**
     * 使用手机号验证码登陆的接口
     */
    public Result login(String phone , String code ,HttpServletRequest request){
        // 获取生成的验证码
        // redis中获取
        String value = tokenManager.getValue(CacheConstants.Cache_KEY + phone);
        if (StringUtils.isBlank(value)){
            throw new ApiRespones(CodeError.CACHE_CODE,CodeError.CACHE_MSG);
        }
        if (!value.equals(code)){
            throw new ApiRespones(CodeError.CODE_ERROR,CodeError.CODE_MSG);
        }
        // 当使用手机号验证码登陆的时候 如果没有该用户信息，系统默认生成固定的用户信息
        AppUser user = getUser(phone);
//        String uuid = String.valueOf(UUID.randomUUID());
        String token = tokenManager.generateToken(user.getUserId().toString());
        return new Result().okTokenSuccess("登陆成功",200,user, String.valueOf(token));
    }

    /**
     * 通过手机号获取用户信息
     */
    public AppUser getUser(String phone){
        QueryWrapper<AppUser> appUserQueryWrapper = new QueryWrapper<>();
        appUserQueryWrapper.eq("phone",phone);
        AppUser appUser = appUserMapper.selectOne(appUserQueryWrapper);
        if (appUser == null){

            // 添加用户默认信息
            AppUser appuser = new AppUser();
            appuser.setAccount("lcj-"+phone);
            appuser.setPhone(phone);
            appuser.setPassWord("123456");
            appuser.setCancel(0L);
            // 添加
            appUserService.save(appuser);
        }
        AppUser appUserServiceOne = appUserMapper.selectOne(appUserQueryWrapper);
        return appUserServiceOne;
    }

    /**
     * 账号密码登陆
     * @return
     */
    public Result userLogin(String account, String password){
        QueryWrapper<AppUser> appUserQueryWrapper = new QueryWrapper<>();
        appUserQueryWrapper.eq("account",account).eq("password",password);
        AppUser appUserServiceOne = appUserMapper.selectOne(appUserQueryWrapper);
        if (null == appUserServiceOne){
            throw new ApiRespones(CodeError.USER_CODE,CodeError.USER_MSG);
        }
        // 存入到redis
        String token = tokenManager.generateToken(appUserServiceOne.getUserId().toString());
        return new Result().okTokenSuccess("登陆成功",200,appUserServiceOne,token);
    }

    /**
     * 注销功能
     * @param userId 用户id
     * @return
     */
    public Result CancelOut( int userId){
        // 删除redis里的数据
        tokenManager.deleteToken(userId);
        boolean b = appUserService.removeById(userId);
        return new Result().success("注销成功",200,b);
    }

    /**
     * 退出登陆
     * @param request
     * @return
     */
    public Result layout(HttpServletRequest request) {
        String token = request.getHeader("token");
         tokenManager.layoutToken(token);
         return new Result().ok("退出成功",0);
    }


}
